package modules::cuffdiff_recursive;
use strict;
use lib '/usr/users/ga002/corpasm/workarea/src/lib/Math-Combinatorics-0.09/lib/';
use Math::Combinatorics;

sub new {
  my ($class,$config)    = @_;

  my $self = {
               'util' => $config,
             };
  bless $self,$class;
  return $self;
}

sub prepare {
  my $self  = shift;
  my $util                   = $self->{'util'};
  my $job_name               = $util->{'_job_name'};
  my $path                   = $util->{'_path'};
  my $cuffdiff_recursive_dir = $util->{'_cuffdiff_recursive_dir' };

  print "Creating '$cuffdiff_recursive_dir'...\n"; 
  mkdir  $cuffdiff_recursive_dir, 777; chmod(0777, $cuffdiff_recursive_dir);
  
  return;
}

sub run {
  my $self                   = shift;
  my $util                   = $self->{'util'};
  my $cuffdiff_recursive_dir = $util->{'_cuffdiff_recursive_dir' };
  my $genome                 = $util->{'_genome'       };
  my $tophat_dir             = $util->{'_tophat_dir'   };
  my $samples                = $util->{'_samples'      };
  my $gtf                    = $util->{'_gtf_file'     };
  my $cond                   = $util->{'_cond'         };

  my ($cmd,$conditions); 
  my $i=0;
  # keys are labels, values are libraries
  
  my ($cmd_lib,$cmd_label,$cases);
  
  foreach my $smpls (@$samples) {
    my @smpls_path;
    map {push @smpls_path,"$tophat_dir/$_/accepted_hits.bam"} @$smpls;
    push @$cases,join (',',@smpls_path);
  } 
  my %dat;
  @dat{@$cond} = @$cases; 
  
#  my @all_combinations_of_samples = map { combine($_,@$samples) } 1..@$samples;
  my ($seen1,$seen2);

  foreach my $cmp1 (keys %dat) {
    foreach my $cmp2 (keys %dat) {
      if($cmp1 ne $cmp2) { 
        #print "$cmp1\t$cmp2\n";
        $seen1->{$cmp1}{$cmp2} = 1;
        $seen2->{$cmp2}{$cmp1} = 1;
      }
    }
  }
  use Data::Dumper;
  #warn Dumper $seen1;
  #warn Dumper $seen2;
  foreach my $keys1 (keys %$seen1) {
    foreach my $keys2 (keys %$seen2) {
      my ($hash1,$hash2) = ($seen1->{$keys1},$seen2->{$keys2});
      warn Dumper $hash1;
      warn Dumper $hash2;
    }
  }

  
  map {$cmd_lib .= "$_ "} @$cases;
  $cmd_label = join (',',@$cond);

  $cmd = qq(bsub -J cuffdiff_recursive.glob -n 8 -R "span[ptile=8] rusage[mem=5000]" )
       . qq(" /usr/users/ga002/corpasm/workarea/bin/cuffdiff -o $cuffdiff_recursive_dir)
       . qq( -b $genome.fa -p 8 )
       . qq( -L $cmd_label -u $gtf )
       . qq( $cmd_lib");
  #print "\n\nRUNNING COMMAND:\n$cmd\n\n";
  
  
  #warn Dumper \%dat;

  #warn Dumper $conditions;
  #system($cmd);
  my $utility = modules::utilities->new();
  $utility->check_completion('cuffdiff');
  return;

}
1; 


